package com.shuorikeji.huohuo.utils;

import android.app.Dialog;
import android.content.Context;
import android.net.http.SslError;
import android.os.Build;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.adapter.JbTypeAdapter;
import com.shuorikeji.huohuo.adapter.MhMlAdapter;
import com.shuorikeji.huohuo.bean.BaseCallBackBean;
import com.shuorikeji.huohuo.bean.JbTypeBean;
import com.shuorikeji.huohuo.bean.MhZjInfoBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.view.GridDividerItemDecoration;

import java.math.BigDecimal;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


public class DialogUtil {
    /**
     * 加载进度弹窗
     *
     * @param context 上下文
     * @return dialog
     */
    public static Dialog showLoadingDialog(Context context) {
        Dialog loadingDialog = new Dialog(context, R.style.dialog_loading_style);
        View view = View.inflate(context, R.layout.loading_new_layout, null);
        // 设置自定义的布局
        loadingDialog.setContentView(view);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(context).getScreenWidth() * 0.85f);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialogWindow.setAttributes(lp);
        return loadingDialog;
    }

    public static Dialog showYszc(Context context, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg, R.layout.dialog_ys_rule_layout,
                0.85, 0.6, Gravity.CENTER);
        TextView tvNoAgree = customDialog.findViewById(R.id.tv_no_agree);
        WebView wvContent = customDialog.findViewById(R.id.wv_content);
        TextView tvAgree = customDialog.findViewById(R.id.tv_agree);
        BusinessUtils.setTxtFold(tvAgree, true);
        wvContent.clearCache(true);
        WebSettings settings = wvContent.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setTextZoom(80);
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);
        settings.setDisplayZoomControls(false); // 设置显示缩放按钮(minsdk=11)
        settings.setBuiltInZoomControls(true);   //设置支持缩放
        settings.setAppCacheEnabled(false);
        settings.setSupportZoom(true);

        wvContent.setOverScrollMode(View.OVER_SCROLL_NEVER);//webview滚动拖动到顶部或底部阴影
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(wvContent, true);        //跨域cookie读取
        }
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setBlockNetworkImage(false);
        settings.setAllowFileAccess(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
            settings.setAllowUniversalAccessFromFileURLs(true);
        }
        wvContent.setWebChromeClient(new MyWebChromeClient());//设置可alert弹窗
        wvContent.setWebViewClient(new MyWebViewClient());
        wvContent.loadUrl(Constant.YS_RULE);
        tvNoAgree.setOnClickListener(view -> {
            callBack.onClick(1, null);
            customDialog.dismiss();
        });
        tvAgree.setOnClickListener(view -> {
            callBack.onClick(2, null);
            customDialog.dismiss();
        });
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }

    public static class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {

            }
        }
    }

    public static class MyWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //移除H5页面中的标题
            if (url.endsWith("zlH5R") || url.endsWith("zlH5W") || url.contains("zlH5") || url.contains("rightDesc")) {
                //编写 javaScript方法
                String javascript = "javascript:function hideOther() {" +
                        "var headers = document.getElementsByTagName('header');" +
                        "var lastHeader = headers[headers.length-1];" +
                        "lastHeader.remove();" +
                        "}";
                //创建方法
                view.loadUrl(javascript);
                //加载方法
                view.loadUrl("javascript:hideOther();");
            }
        }
    }

    public static Dialog showBookJj(Context context, String content, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg, R.layout.dialog_book_desc_layout,
                0.85, 0.5, Gravity.CENTER);
        TextView tvTitle = customDialog.findViewById(R.id.tv_title);
        TextView tvContent = customDialog.findViewById(R.id.tv_content);
        ImageView ivClose = customDialog.findViewById(R.id.iv_close);
        BusinessUtils.setTxtFold(tvTitle, true);
        ivClose.setOnClickListener(view -> {
            customDialog.dismiss();
        });
        tvContent.setText(Html.fromHtml(content));
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }

    public static Dialog showShareDialog(Context context, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg_bottom_top, R.layout.dialog_share_layout,
                1.0, 0.0, Gravity.BOTTOM);
        TextView tvTitle = customDialog.findViewById(R.id.tv_title);
        LinearLayout llQQSc = customDialog.findViewById(R.id.ll_qq_sc);
        LinearLayout llWxHy = customDialog.findViewById(R.id.ll_wx_hy);
        LinearLayout llWxSc = customDialog.findViewById(R.id.ll_wx_sc);
        TextView tvCancel = customDialog.findViewById(R.id.tv_cancel);
        BusinessUtils.setTxtFold(tvTitle, true);
        llQQSc.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(1, null);
        });
        llWxHy.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(2, null);
        });
        llWxSc.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(3, null);
        });
        tvCancel.setOnClickListener(view -> {
            customDialog.dismiss();
        });
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }

    static JbTypeAdapter jbTypeAdapter;

    public static Dialog showJb(Context context, List<JbTypeBean> typeList, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg, R.layout.dialog_jb_layout,
                0.85, 0.5, Gravity.CENTER);
        TextView tvTitle = customDialog.findViewById(R.id.tv_title);
        RecyclerView rvType = customDialog.findViewById(R.id.rv_type);
        EditText etContent = customDialog.findViewById(R.id.et_content);
        TextView tvQx = customDialog.findViewById(R.id.tv_qx);
        TextView tvTj = customDialog.findViewById(R.id.tv_submit);
        BusinessUtils.setTxtFold(tvTitle, true);

        rvType.setLayoutManager(new GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false));
        rvType.addItemDecoration(new GridDividerItemDecoration(20));
        jbTypeAdapter = new JbTypeAdapter(context, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        JbTypeBean data = (JbTypeBean) object;
                        for (int i = 0; i < typeList.size(); i++) {
                            if (data.getType().equals(typeList.get(i).getType())) {
                                typeList.get(i).setSec(true);
                            } else {
                                typeList.get(i).setSec(false);
                            }
                        }
                        jbTypeAdapter.setData(typeList);
                        break;
                }
            }
        });
        rvType.setAdapter(jbTypeAdapter);
        jbTypeAdapter.setData(typeList);

        tvQx.setOnClickListener(view -> {
            customDialog.dismiss();
        });
        tvTj.setOnClickListener(view -> {
            BaseCallBackBean data = new BaseCallBackBean();
            for (int i = 0; i < typeList.size(); i++) {
                if (typeList.get(i).isSec()) {
                    data.setJbType(typeList.get(i).getType());
                    break;
                }
            }
            data.setJbContent(etContent.getText().toString());
            callBack.onClick(1, data);
            customDialog.dismiss();
        });
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }

    static MhMlAdapter mhMlAdapter;

    public static Dialog showMhMlDialog(Context context, List<MhZjInfoBean> mhZjList, int allZj, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg_bottom_top, R.layout.dialog_mh_ml_layout,
                1.0, 0.65, Gravity.BOTTOM);
        TextView tvTitle = customDialog.findViewById(R.id.tv_title);
        ImageView ivClose = customDialog.findViewById(R.id.iv_close);
        TextView tvNewZj = customDialog.findViewById(R.id.tv_new_zj);
        TextView tvAllZj = customDialog.findViewById(R.id.tv_all_zj);
        RecyclerView rvData = customDialog.findViewById(R.id.rv_data);
        ImageView ivSyz = customDialog.findViewById(R.id.iv_syz);
        ImageView ivXyz = customDialog.findViewById(R.id.iv_xyz);
        BusinessUtils.setTxtFold(tvTitle, true);
        tvNewZj.setText("最新话 - 第" + allZj + "话");
        tvAllZj.setText("全部章节（" + allZj + "）");
        rvData.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        mhMlAdapter = new MhMlAdapter(context, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        MhZjInfoBean data = (MhZjInfoBean) object;
                        customDialog.dismiss();
                        callBack.onClick(3, data);
                        break;
                }
            }
        });
        rvData.setAdapter(mhMlAdapter);
        mhMlAdapter.setData(mhZjList);
        ivClose.setOnClickListener(view -> {
            customDialog.dismiss();
        });
        ivSyz.setOnClickListener(view -> {
            callBack.onClick(1, null);
        });
        ivXyz.setOnClickListener(view -> {
            callBack.onClick(2, null);
        });
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }

    /**
     * 更新漫画目录
     */
    public static void gxMhZjInfo(List<MhZjInfoBean> mhZjList) {
        if (mhMlAdapter != null) {
            mhMlAdapter.setData(mhZjList);
        }
    }

    public static Dialog showMhSetDialog(Context context, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg_bottom_top, R.layout.dialog_see_mh_set_layout,
                1.0, 0.0, Gravity.BOTTOM);
        SeekBar sbLight = customDialog.findViewById(R.id.sb_light);
        ImageView ivSystemLight = customDialog.findViewById(R.id.iv_light_system);
        LinearLayout llJzType = customDialog.findViewById(R.id.ll_jz_type);
        LinearLayout llPtType = customDialog.findViewById(R.id.ll_pt_type);
        LinearLayout llRmType = customDialog.findViewById(R.id.ll_rm_type);
        LinearLayout llHp = customDialog.findViewById(R.id.ll_hp);
        LinearLayout llSp = customDialog.findViewById(R.id.ll_sp);
        TextView tvQxdLc = customDialog.findViewById(R.id.tv_qxd_lc);
        TextView tvQxdGq = customDialog.findViewById(R.id.tv_qxd_gq);
        RelativeLayout rlQxdCq = customDialog.findViewById(R.id.rl_qxd_cq);
        ImageView ivQxdCqVip = customDialog.findViewById(R.id.iv_qxd_vip);
        ImageView ivHp=customDialog.findViewById(R.id.iv_hp);
        ImageView ivSp=customDialog.findViewById(R.id.iv_sp);
        sbLight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                BigDecimal bigDecimal = BusinessUtils.divBigDecimal(new BigDecimal(i), new BigDecimal(10), 1, false);
                ivSystemLight.setImageResource(R.mipmap.icon_swtich_close);
                callBack.onClick(1, bigDecimal.floatValue());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        ivSystemLight.setOnClickListener(view -> {
            ivSystemLight.setImageResource(R.mipmap.icon_swtich_open);
            callBack.onClick(2, null);
        });
        llJzType.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(3, null);
        });
        llPtType.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(4, null);
        });
        llRmType.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(5, null);
        });
        llHp.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(6, null);
            ivHp.setImageResource(R.mipmap.icon_hp_light);
            ivSp.setImageResource(R.mipmap.icon_sp_gray);
        });
        llSp.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(7, null);
            ivHp.setImageResource(R.mipmap.icon_see_mh_hp_un_sec);
            ivSp.setImageResource(R.mipmap.icon_see_mh_sp_sec);
        });
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }

    public static Dialog showShareAppDialog(Context context,String yqm, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg_bottom_top, R.layout.dialog_share_app_layout,
                0.8, 0.0, Gravity.CENTER);
        TextView tvTitle = customDialog.findViewById(R.id.tv_title);
        ImageView ivClose = customDialog.findViewById(R.id.iv_close);
        ImageView ivEwm=customDialog.findViewById(R.id.iv_ewm);
        ivEwm.setImageBitmap(BusinessUtils.getQRCode("https://app.hctonghui.com/h5/#/?invite=" + yqm, 200, 200));
        BusinessUtils.setTxtFold(tvTitle, true);
        ivClose.setOnClickListener(view -> {
            customDialog.dismiss();
        });
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }

    public static Dialog showXgNcDialog(Context context, String nc, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg_bottom_top, R.layout.dialog_xg_nc_layout,
                0.8, 0.0, Gravity.CENTER);
        EditText etContent = customDialog.findViewById(R.id.et_content);
        TextView tvQx = customDialog.findViewById(R.id.tv_qx);
        TextView tvXg = customDialog.findViewById(R.id.tv_xg);
        BusinessUtils.setTxtFold(tvXg, true);
        etContent.setText(nc);
        tvQx.setOnClickListener(view -> {
            customDialog.dismiss();
        });
        tvXg.setOnClickListener(view -> {
            if (BusinessUtils.isEmpty(etContent.getText().toString())) {
                callBack.onClick(1, "请输入昵称");
            } else {
                callBack.onClick(2, etContent.getText().toString());
                customDialog.dismiss();
            }
        });
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }

    public static Dialog showJsAdDialog(Context context, ClickCallBack callBack) {
        CustomDialog customDialog = new CustomDialog(context, R.style.DialogNoTitleStyleTranslucentBg_bottom_top, R.layout.dialog_js_ad_layout,
                0.8, 0.0, Gravity.CENTER);
        EditText etContent = customDialog.findViewById(R.id.et_content);
        TextView tvQx = customDialog.findViewById(R.id.tv_qx);
        TextView tvOk = customDialog.findViewById(R.id.tv_ok);
        tvQx.setOnClickListener(view -> {
            customDialog.dismiss();
            callBack.onClick(1, null);
        });
        tvOk.setOnClickListener(view -> {
            callBack.onClick(2, null);
            customDialog.dismiss();
        });
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
        return customDialog;
    }
}
